package school.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import school.domain.Info;
import school.domain.Life;
import school.mapper.LifeMapper;
import school.support.BaseController;
import school.support.pojo.LifePo;
import school.support.util.ParamUtils;
import tk.mybatis.mapper.entity.Example;

@RequestMapping("life")
@Controller
public class LifeController extends BaseController {

    @Autowired
    private LifeMapper lifeMapper;

    /**
     * 生活档案列表
     *
     * @param lifePo
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping("list")
    private String list(LifePo lifePo, @RequestParam(defaultValue = "1") Integer pageNum, Model model) {
        Example example = new Example(Info.class);
        Example.Criteria criteria = example.createCriteria();
        if (lifePo.getUsername() != null) {
            criteria.andCondition("u.name like '%" + lifePo.getUsername() + "%'");
        }
        /**
         * 如果是医生     只能看到自己负责的用户
         */
        if (sessionUser().getType().equalsIgnoreCase("doctor")) {
            criteria.andCondition("u.doctor = '" + sessionUser().getId() + "'");
        }
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<LifePo> pageInfo = new PageInfo<>(lifeMapper.selectPoByExample(example), 5);
        model.addAttribute(pageInfo);
        model.addAttribute("url", request.getRequestURI() + "?" + ParamUtils.params2String(request));
        return "life/list";
    }

    /**
     * 生活档案详情
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Life life = null;
        if (id == 0) {
            Integer userid = sessionUser().getId();
            life = lifeMapper.selectByUser(userid);
        } else {
            life = lifeMapper.selectByPrimaryKey(id);
        }
        if(life == null) life = new Life();
        model.addAttribute("life", life);
        return "life/detail";
    }

    /**
     * 修改信息
     *
     * @param life
     * @return
     */
    @RequestMapping("update")
    public String update(Life life) {
        if (life.getId() == null || life.getId() == 0) {
            life.setUserid(sessionUser().getId());
            lifeMapper.insertSelective(life);
        } else {
            lifeMapper.updateByPrimaryKeySelective(life);
        }

        return refresh();
    }


}
